package com.itic.mall.mobile.pay;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.type.PayType;
import com.itic.appbase.framework.utils.AliPayUtil;
import com.itic.appbase.framework.utils.PayVo;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.WeixinPayUtil;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.orders.detail.persistence.model.OrdersDetail;
import com.itic.mall.system.orders.detail.service.OrdersDetailService;
import com.itic.mall.system.orders.item.persistence.model.OrdersItem;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;


@Controller
@RequestMapping(value="/mobile/alipay")
public class AliPayInterface
     extends BaseMobileInterface {
	
	@Autowired
	private OrdersDetailService ordersDetailService;
	
	/**
	 * 支付宝支付成功回调
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/success")   
	@ResponseBody 
	public void notify(HttpServletRequest request,HttpServletResponse response){  
		 try{  
             //处理自己的业务逻辑  
			 PaySuccessVo paySuccessVo = AliPayUtil.success(request, getAlipayConfig());//获取订单号码
			 String orderNum = paySuccessVo.getOrderNo();
			 String payNo = paySuccessVo.getPayNo();
			 String payTime = paySuccessVo.getPayTime();
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
			 Date date = sdf.parse(payTime); 
			 //这里调用服务层处理逻辑
			 String dealResult = FAIL;		  
			 //处理用户订单状态为已支付状态
			 
			// dealResult = dealOrderByorderNo(orderNum,payNo,date,"001");//支付类型（001：支付宝，002：微信，003：余额）		 
			 dealResult = this.ordersDetailService.aliPaySuccess(orderNum, payNo, PayType.alipay, new Date());
			 if(SUCCESS.equals(dealResult)){
				 //System.out.println("success");//通知支付宝的服务器已经成功了
			 }
          }catch(Exception e){  
        	  logException("AliPayInterface", "notify", e.toString(),"支付宝回调",e);
          } 
	}  
	
	/**
	 * 支付宝支付
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param orderNum
	 * @return
	 */
	@RequestMapping(value="/pay")
	@ResponseBody
	public Map<String,Object> pay( HttpServletRequest request,HttpServletResponse response, String token,String appId,String orderNo ){
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(orderNo) ){
				UsersMall user = getUsersByTokenAndAppId(token, appId);
				if( null != user ){
					String userId = user.getId();
			    	OrdersDetail ordersDetail = getOrderByOrderNo(userId,orderNo,"1");
			    	String orderDesc = getDescByOrderNo(orderNo);
			    	if(ordersDetail !=null ){
						orderDesc = ordersDetail.getUserNickName() +"在"+ordersDetail.getCreateTime()+"购买商品"+orderDesc;
						//验证订单
						//Order order = verifyOrder(user.getId(),orderNum);
						PayVo payVo = new PayVo();
						payVo.setDesc(orderDesc);
						payVo.setOrderNum(orderNo);
						payVo.setTotalMoney(ordersDetail.getActualPay().toString());
				        String data = AliPayUtil.pay(request, getAlipayConfig(),payVo);
				        resultMap.put(DATA, data);
						errorCode = SUCCESS_ERROR_CODE;
				    	errorMsg = SUCCESS_ERROR_MSG;
					}else{
						errorCode = ORDER_ERROR_CODE;
						errorMsg = ORDER_ERROR_MSG;
					}
				}else{
					errorCode = LOGIN_ERROR_CODE;
			    	errorMsg = LOGIN_ERROR_MSG;
				}
			}
		}catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	logException("AliPayInterface", "pay", e.toString(),"支付宝支付",e);
		}
    	resultMap.put(CODE, errorCode);
    	resultMap.put(MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}
	/**
	 * 支付宝批量付款回调
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/successCompany")
	@ResponseBody
	public void notifyCompany(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			// 处理自己的业务逻辑
			CompanyPaySuccessVo companyPaySuccessVo = AliPayUtil.successCompany(request, getAlipayCompanyConfig());
			/*
			 * 格式为：流水号^收款方账号^收款账号姓名^付款金额^成功标识(S)^成功原因(null)^支付宝内部流水号^完成时间。
			 * 每条记录以“|”间隔
			 */
			String success_details = companyPaySuccessVo.getSuccess_details();
			String[] strDetails = success_details.split("|");
			String dealResult = FAIL;
			
			if (SUCCESS.equals(dealResult)) {
				System.out.println("success");// 通知支付宝的服务器已经成功了
			}
		} catch (Exception e) {
			logException("AliPayInterface", "notifyCompany", e.toString(), "支付宝批量付款回调", e);
		}
	}
	/**
	 * 支付宝批量支付
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value = "/companypay")
	@ResponseBody
	public Map<String, Object> companypay(HttpServletRequest request, HttpServletResponse response,
			String orderNoSkuIds) {
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			//orderNoSkuIds格式，orderNo:skuId:aliId:realName,orderNo:skuId:aliId:realName,orderNo:skuId:aliId:realName
			/*
			 * 付款的详细数据，最多支持1000笔。
			 * 
			 * 格式为：流水号1^收款方账号1^收款账号姓名1^付款金额1^备注说明1|流水号2^收款方账号2^收款账号姓名2^付款金额2^
			 * 备注说明2。
			 * 
			 * 每条记录以“|”间隔。
			 * 
			 * 流水号不能超过64字节，收款方账号小于100字节，备注不能超过200字节。当付款方为企业账户，且转账金额达到（大于等于）
			 * 50000元，备注不能为空。
			 * 0315006^testture0002@126.com^常炜买家^20.00^hello
			 */
			// 根据订单号获取订单描述
			String batch_no = RandomOrderNumHelper.getOrderNumber();//批量付款批次号
			String itemDesc = null;
			String[] stringSrc = orderNoSkuIds.split(",");
			Integer batchNum = stringSrc.length;//付款总笔数 批量付款笔数（最少1笔，最多1000笔）。
			Double batch_fee = 0.0;
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String pay_date = sdf.format(date);
			String detail_data = null;
			for(int i=0;i<stringSrc.length;i++){
				String serial = RandomOrderNumHelper.getOrderNumber();
				String[] orderSrc = stringSrc[i].split(":");
				String orderNo = orderSrc[0];
				String skuId = orderSrc[1];
				String aliId = orderSrc[2];
				String realName = orderSrc[3];
				//判断订单是否已付款
				
				
				OrdersItem ordersItem = getorderItem(orderNo,skuId);
				String actualPay = ordersItem.getActualPay().toString();
				//将退款流水记录到退款日志表中
				
				//公司支付日志表中同步用户日志表退款记录
				
				batch_fee = batch_fee + ordersItem.getActualPay();
				itemDesc = getOrdersItemDesc(orderNo,skuId);
				if(i!=stringSrc.length-1){
					if(i!=0){
						detail_data = detail_data + serial+"^"+aliId+"^"+realName+"^"+actualPay+"^"+itemDesc+"|";
					}else{
						detail_data = serial+"^"+aliId+"^"+realName+"^"+actualPay+"^"+itemDesc;
					}
				}else{
					if(i!=0){
						detail_data = detail_data + serial+"^"+aliId+"^"+realName+"^"+actualPay+"^"+itemDesc;
					}else{
						detail_data = serial+"^"+aliId+"^"+realName+"^"+actualPay+"^"+itemDesc;
					}
				}
			}
			CompanyPayVo companyPayVo = new CompanyPayVo();
			companyPayVo.setBatch_fee(batch_fee.toString());
			companyPayVo.setBatch_no(batch_no);
			companyPayVo.setBatch_num(batchNum.toString());
			companyPayVo.setDetail_data(detail_data);
			companyPayVo.setPay_date(pay_date);
			String data = AliPayUtil.companyPay(request, getAlipayCompanyConfig(), companyPayVo);
			
			resultMap.put(DATA, data);
			errorCode = SUCCESS_ERROR_CODE;
	    	errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("AliPayInterface", "companypay", e.toString(), "支付宝批量支付", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	/**
	 * 微信退款
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param orderNum
	 * @return
	 */
	@RequestMapping(value="/back")
	@ResponseBody
	public Map<String,Object> back( HttpServletRequest request,HttpServletResponse response, String token,String appId,String orderNum ){
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(orderNum) ){
			UsersMall user = getUsersByTokenAndAppId(token, appId);
			if( null != user ){
				//验证订单
				//Order order = verifyOrder(user.getId(),orderNum);
				PayVo payVo = new PayVo();
				payVo.setDesc("测试");
				payVo.setOrderNum(orderNum);
				payVo.setTotalMoney("0");
		        WeixinPayUtil.back(request, getWxpayConfig(),payVo);
		        
				errorCode = SUCCESS_ERROR_CODE;
		    	errorMsg = SUCCESS_ERROR_MSG;
			}else{
				errorCode = LOGIN_ERROR_CODE;
		    	errorMsg = LOGIN_ERROR_MSG;
			}
		}
    	resultMap.put(CODE, errorCode);
    	resultMap.put(MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}
	
}